<template>
	<view class="community-container">
		<!-- 页面标题 -->
		 <custom-nav-bar title="社区动态"></custom-nav-bar>
		<view class="page-header">
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<uni-icons type="spinner-cycle" size="40" color="#1989fa" animation="spin"></uni-icons>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 错误提示 -->
		<view v-else-if="error" class="error-container">
			<uni-icons type="close-circle" size="40" color="#ee0a24"></uni-icons>
			<text class="error-text">{{ error }}</text>
			<button @click="fetchArticles" class="retry-btn">重试</button>
		</view>

	<!-- 文章列表 -->
	<view v-else-if="articles.length > 0" class="article-list">
		<view v-for="article in articles" :key="article.articleId" class="article-item" @click="goToDetail(article)">
			<!-- 头像和内容区域 -->
			<view class="article-main">
				<!-- 左侧头像 -->
				<view class="avatar-column">
					<image :src="article.author?.avatar || '/static/logo.png'" mode="aspectFill" class="avatar"></image>
				</view>
				
				<!-- 右侧内容 -->
				<view class="content-column">
					<!-- 用户名和时间 -->
					<view class="user-header">
						<text class="username">{{ article.author?.username || '未知作者' }}</text>
						<text class="time-dot">·</text>
						<text class="publish-time">{{ formatDate(article.createdAt || article.publishTime) }}</text>
					</view>
					
					<!-- 文章标题（如果有） -->
					<view v-if="article.title" class="article-title">{{ article.title }}</view>
					
					<!-- 文章内容 -->
					<view class="article-text" v-html="formatHtmlContent(article.content, 150)"></view>
					
					<!-- 封面图片（如果有） -->
					<view v-if="article.coverImage" class="article-image">
						<image :src="article.coverImage" mode="aspectFill"></image>
					</view>
					
					<!-- 互动按钮 -->
					<view class="article-actions">
						<view class="action-btn" @click.stop="goToDetail(article)">
							<uni-icons type="chatbubble" size="18" color="#536471"></uni-icons>
							<text>{{ article.commentCount || 0 }}</text>
						</view>
						<view class="action-btn" @click.stop="toggleFavorite(article)">
							<uni-icons 
								:type="article.isFavorited ? 'star-filled' : 'star'" 
								size="18" 
								:color="article.isFavorited ? '#FFD700' : '#536471'"
							></uni-icons>
							<text>{{ article.favoriteCount || 0 }}</text>
						</view>
						<view class="action-btn" @click.stop="toggleLike(article)">
							<uni-icons 
								:type="article.isLiked ? 'heart-filled' : 'heart'" 
								size="18" 
								:color="article.isLiked ? '#F91880' : '#536471'"
							></uni-icons>
							<text>{{ article.likeCount || 0 }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>

		<!-- 空状态 -->
		<view v-else class="empty-container">
			<uni-icons type="document" size="60" color="#c0c4cc"></uni-icons>
			<text class="empty-text">暂无文章</text>
		</view>
		
		<!-- 悬浮聊天按钮 -->
		<chat-bt :show-pulse="true"></chat-bt>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { articleApi } from '../../common/api/index.js'
import ChatBt from '@/components/chat-ai/chat-bt.vue'

// 响应式数据
const articles = ref([])
const loading = ref(false)
const error = ref('')

// 格式化日期
const formatDate = (dateString) => {
	if (!dateString) return '未知时间'
	const date = new Date(dateString)
	const now = new Date()
	const diff = now - date
	
	// 小于1分钟
	if (diff < 60 * 1000) {
		return '刚刚'
	}
	// 小于1小时
	else if (diff < 60 * 60 * 1000) {
		return `${Math.floor(diff / (60 * 1000))}分钟前`
	}
	// 小于24小时
	else if (diff < 24 * 60 * 60 * 1000) {
		return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
	}
	// 小于7天
	else if (diff < 7 * 24 * 60 * 60 * 1000) {
		return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
	}
	// 超过7天显示具体日期
	else {
		return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
	}
}

// 格式化HTML内容，保留HTML标签并限制长度（小程序兼容版本）
const formatHtmlContent = (html, maxLength = 100) => {
	if (!html) return ''
	
	// 使用正则表达式移除HTML标签，获取纯文本内容
	const stripHtmlTags = (str) => {
		return str.replace(/<[^>]+>/g, '')
	}
	
	// 获取纯文本长度（不包括HTML标签）
	const textContent = stripHtmlTags(html)
	
	// 如果内容长度不超过限制，直接返回原始HTML
	if (textContent.length <= maxLength) {
		return html
	}
	
	// 内容超过限制，需要截断并确保HTML标签正确关闭
	let result = ''
	let currentLength = 0
	let tagStack = []
	let i = 0
	
	while (i < html.length && currentLength < maxLength) {
		// 检查是否是HTML标签
		if (html[i] === '<') {
			const endTagIndex = html.indexOf('>', i)
			if (endTagIndex !== -1) {
				const tag = html.substring(i, endTagIndex + 1)
				result += tag
				
				// 处理标签：检查是开始标签还是结束标签
				if (tag.startsWith('</')) {
					// 结束标签，从栈中弹出
					tagStack.pop()
				} else if (!tag.startsWith('<br') && !tag.startsWith('<hr') && !tag.endsWith('/>')) {
					// 开始标签（非自闭合标签），推入栈中
					const tagName = tag.match(/<([a-z][a-z0-9]*)[^>]*>/i)
					if (tagName && tagName[1]) {
						tagStack.push(tagName[1])
					}
				}
				
				i = endTagIndex + 1
			} else {
				// 不是完整的标签，作为普通文本处理
				result += html[i]
				currentLength++
				i++
			}
		} else {
			// 普通文本
			result += html[i]
			currentLength++
			i++
		}
	}
	
	// 添加省略号
	result += '...'
	
	// 关闭所有未闭合的标签
	while (tagStack.length > 0) {
		const tagName = tagStack.pop()
		result += `</${tagName}>`
	}
	
	return result
}

// 切换点赞状态
const toggleLike = async (article) => {
	// 检查是否已登录
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}
	
	const articleId = article.articleId || article.id
	const originalLiked = article.isLiked
	const originalCount = article.likeCount || 0
	
	try {
		let response
		if (originalLiked) {
			// 取消点赞
			response = await articleApi.cancelLike(articleId)
		} else {
			// 点赞
			response = await articleApi.likeArticle(articleId)
		}
		
		if (response.status === 'success' && response.data) {
			// 使用后端返回的数据更新状态
			article.isLiked = response.data.isLiked
			article.likeCount = response.data.likeCount
			
			uni.showToast({
				title: originalLiked ? '已取消点赞' : '点赞成功',
				icon: 'success',
				duration: 1000
			})
		} else {
			uni.showToast({
				title: response.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('点赞操作失败:', err)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}

// 切换收藏状态
const toggleFavorite = async (article) => {
	// 检查是否已登录
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}
	
	const articleId = article.articleId || article.id
	const originalFavorited = article.isFavorited
	const originalCount = article.favoriteCount || 0
	
	try {
		let response
		if (originalFavorited) {
			// 取消收藏
			response = await articleApi.cancelFavorite(articleId)
		} else {
			// 收藏
			response = await articleApi.favoriteArticle(articleId)
		}
		
		if (response.status === 'success' && response.data) {
			// 使用后端返回的数据更新状态
			article.isFavorited = response.data.isFavorited
			article.favoriteCount = response.data.favoriteCount
			
			uni.showToast({
				title: originalFavorited ? '已取消收藏' : '收藏成功',
				icon: 'success',
				duration: 1000
			})
		} else {
			uni.showToast({
				title: response.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('收藏操作失败:', err)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}

// 跳转到文章详情
const goToDetail = (article) => {
	const id = article.articleId || article.id
	uni.navigateTo({
		url: `/pages/community/article-info?id=${id}`
	})
}

// 获取文章列表
const fetchArticles = async () => {
	loading.value = true
	error.value = ''
	try {
		// 调用API获取文章列表
		const response = await articleApi.getArticles({
			page: 1,
			pageSize: 10,
			status: 'published' // 只获取已发布的文章
		})
		
		// 处理响应数据，根据后端返回的数据结构进行调整
		console.log('API响应:', response)
		
		// 适配后端返回格式：{status: 'success', data: {total, items}}
		if (response.status === 'success' && response.data) {
			// 根据提供的JSON格式，实际文章数据在response.data.items数组中
			articles.value = Array.isArray(response.data.items) ? response.data.items : []
			console.log('文章列表数据:', articles.value)
		} else {
			articles.value = []
			error.value = response.message || '获取文章失败'
		}
	} catch (err) {
		console.error('获取文章列表失败:', err)
		error.value = '网络错误，请稍后重试'
	} finally {
		loading.value = false
	}
}

// 页面加载时获取文章列表
onMounted(() => {
	fetchArticles()
})
</script>

<style lang="scss" scoped>
.community-container {
	min-height: 100vh;
	background-color: #ffffff;

	.page-header {
		padding: 10rpx 0;
	}

	.loading-container,
	.error-container,
	.empty-container {
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.loading-text,
		.error-text,
		.empty-text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #909399;
		}
	}

	.error-container {
		.retry-btn {
			margin-top: 30rpx;
			padding: 0 40rpx;
			background-color: #1989fa;
			color: #ffffff;
		}
	}

	// 文章列表 - Twitter风格
	.article-list {
		.article-item {
			background-color: #ffffff;
			padding: 24rpx 30rpx;
			border-bottom: 1px solid #eff3f4;
			transition: background-color 0.2s;
			
			&:active {
				background-color: #f7f9f9;
			}

			// 主要布局：头像 + 内容
			.article-main {
				display: flex;
				
				// 左侧头像列
				.avatar-column {
					margin-right: 24rpx;
					
					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						background-color: #f5f5f5;
						display: block;
					}
				}
				
				// 右侧内容列
				.content-column {
					flex: 1;
					min-width: 0; // 防止flex子元素溢出
					
					// 用户头部信息
					.user-header {
						display: flex;
						align-items: center;
						margin-bottom: 8rpx;
						
						.username {
							font-size: 28rpx;
							font-weight: bold;
							color: #0f1419;
							margin-right: 8rpx;
						}
						
						.time-dot {
							color: #536471;
							margin: 0 8rpx;
							font-size: 24rpx;
						}
						
						.publish-time {
							font-size: 26rpx;
							color: #536471;
						}
					}
					
					// 文章标题
					.article-title {
						font-size: 32rpx;
						font-weight: 600;
						color: #0f1419;
						line-height: 44rpx;
						margin-bottom: 8rpx;
					}
					
					// 文章内容
					.article-text {
						font-size: 28rpx;
						color: #0f1419;
						line-height: 42rpx;
						margin-bottom: 20rpx;
						word-break: break-word;
						overflow-wrap: break-word;
					}
					
					// 文章图片
					.article-image {
						width: 100%;
						border-radius: 24rpx;
						overflow: hidden;
						margin-bottom: 20rpx;
						
						image {
							width: 100%;
							height: 400rpx;
							display: block;
							background-color: #f5f5f5;
						}
					}
					
					// 互动按钮栏
					.article-actions {
						display: flex;
						justify-content: space-between;
						max-width: 600rpx;
						margin-top: 16rpx;
						
						.action-btn {
							display: flex;
							align-items: center;
							gap: 12rpx;
							padding: 10rpx 16rpx;
							border-radius: 30rpx;
							transition: background-color 0.2s;
							
							text {
								font-size: 24rpx;
								color: #536471;
							}
							
							&:active {
								background-color: rgba(29, 155, 240, 0.1);
							}
						}
					}
				}
			}
		}
	}
}
</style>
